<template>
  <div>
    <!-- 面包屑导航 -->
    <bread />

    <!-- 卡片内容区域 -->
    <el-card>
      <!-- 消息提示 -->
      <el-alert title="添加商品信息" type="info" center show-icon></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 标签页 -->
      <el-form
        :model="addForm"
        :rules="rules"
        ref="addFormRef"
        label-position="top"
        label-width="100px"
      >
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          style="height: 600px;"
          :before-leave="handleLeave"
          @tab-click="handleClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="{
                    expandTrigger: 'hover',
                    value: 'cat_id',
                    label: 'cat_name',
                    children: 'children'
                }"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyTableDate" :key="item.attr_id" :label="item.attr_name">
              <!-- 多选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(itemAttr, index) in item.attr_vals"
                  :key="index"
                  :label="itemAttr"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyTableDate" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片 -->
            <el-upload
              class="upload-demo"
              action="https://www.liulongbin.top:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headers"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button class="btn" type="primary" @click="handleAdd">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 预览图片的弹出框 -->
      <el-dialog :visible.sync="imgDialogVisible" width="80%">
        <img :src="previewImg" alt />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import bread from "../bread";
import API from "../API/Api"
export default {
  props: [],
  components: { bread },
  data() {
    return {
      activeIndex: "0",
      // 定义添加数据
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: ""
      },
      // 验证规则
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ]
      },
      // 商品分类数据
      cateList: [],
      // 动态参数
      manyTableDate: [],
      // 静态属性
      onlyTableDate: [],
      // token值
      headers: {
        Authorization: this.$store.state.token
      },
      // 预览图片的路径
      previewImg: "",
      // 预览图片弹出框的状态
      imgDialogVisible: false
    };
  },
  mounted() {
    this.getCateList();
  },
  methods: {
    // 商品分类数据
    getCateList() {
      API.getCateList().then(res => {
        // console.log(res);
        this.cateList = res.data;
      });
    },
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },
    // 判断是否有分类参数
    handleLeave(activeName, oldActiveName) {
      if (activeName !== 0 && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请选择分类参数");
        return false;
      }
    },
    // 点击tabs
    handleClick() {
      // 动态参数
      if (this.activeIndex === "1" && this.manyTableDate.length === 0) {
        API
          .handleClick(this.addForm.goods_cat[2])
          .then(res => {
            // console.log(res);
            res.data.forEach(item => {
              item.attr_vals = item.attr_vals.split(",");
            });
            this.manyTableDate = res.data;
          });
      }
      // 静态属性
      if (this.activeIndex === "2" && this.onlyTableDate.length === 0) {
        API
          .handleClicks(this.addForm.goods_cat[2])
          .then(res => {
            this.onlyTableDate = res.data;
          });
      }
    },
    // 预览图片
    handlePreview(preFile) {
      // 得到图片的路径
      this.previewImg = preFile.response.data.url;
      // 弹出预览图片的弹出框
      this.imgDialogVisible = true;
    },
    // 删除图片
    handleRemove(delFile) {
      let index = this.addForm.pics.findIndex(item => {
        return item.pic == delFile.response.data.tmp_path;
      });
      // console.log(index);
      this.addForm.pics.splice(index, 1);
    },
    handleSuccess(res) {
      // console.log(res);
      this.addForm.pics.push({
        pic: res.data.tmp_path
      });
    },
    // 添加数据
    handleAdd() {
      // 验证
      this.$refs["addFormRef"].validate(valid => {
        if (valid) {
          let form = this.deepClone(this.addForm);
          form.goods_cat = form.goods_cat.join(",");
          form.attrs = [];
          this.manyTableDate.forEach(item => {
            form.attrs.push({
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(",")
            });
          });
          this.onlyTableDate.forEach(item => {
            form.attrs.push({
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            });
          });
          API.handleAdd(form).then(res => {
            if (res.meta.status == 201) {
              this.$message.success(res.meta.msg);
              this.$router.push("/goods");
            } else {
              this.$message.error(res.meta.msg);
            }
          });
        } else {
          this.$message.error("请填写必要的选项！");
          return false;
        }
      });
    },
    // 深拷贝对象
    deepClone(obj) {
      if (typeof obj !== "object" || obj == null) {
        return obj;
      }
      let result;
      if (obj instanceof Array) {
        result = [];
      } else {
        result = {};
      }
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          result[key] = this.deepClone(obj[key]);
        }
      }
      return result;
    }
  },
  computed: {},
  filters: {},
  watch: {}
};
</script>

<style scoped>
.el-steps {
  margin-top: 15px;
}
.el-tabs {
  margin-top: 15px;
}
.btn {
  margin-top: 10px;
}
</style>